include("shared.lua")
include("sh_player.lua")
include("banned_props.lua")
AddCSLuaFile("shared.lua")
AddCSLuaFile("sh_player.lua")
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("nightvision.lua")

function SendName(ply)
	SendUserMessage("GetName",ply,ply:GetNWString("rpname"))
end
concommand.Add("SendName",SendName)

function SendCred(ply)
	SendUserMessage("GetCred",ply,tostring(ply:GetNWInt("money")))
end
concommand.Add("SendCred",SendCred)

-- Player Join --
function GM:PlayerInitialSpawn(ply)
	ply:SetTeam(1)
	ply:Spawn()
	Loadout(ply)
	ply:PrintMessage(HUD_PRINTTALK,"Welcome to the server, "..ply:Nick()..". Please roleplay nicely.")
	timer.Create("Steam_id_delay", 1, 1, function()
		ply:SetNetworkedString("unique_id",tostring(ply:SteamID()))
		timer.Create("SaveStat",30,0,function() saveStat(ply) end)
		player_exists(ply)
		SendName(ply)
		SendCred(ply)
		end)
	Log(ply:Nick().." joined the server.")
	SendDoorInfo(ply)
end

function ChName(ply,cmd,name)
	ply:SetRPName(name[1])
end
concommand.Add("rp_name",ChName)

function Buy(ply,cmd,args)
	for k,v in pairs(JobItems[ply:Team()]) do
		if(table.HasValue(JobItems[ply:Team()][k],args[1]) and ply:CheckFunds(JobItems[ply:Team()][k][2])) then
			ply:TakeMoney(JobItems[ply:Team()][k][2])
			local item=ents.Create(args[1])
			local tr=ply:GetEyeTraceNoCursor()
			item:SetPos(tr.HitPos+tr.HitNormal*32)
			item:Spawn()
			Log(ply:Nick().." bought a "..args[1]..".")
		end
	end
end
concommand.Add("rp_buy",Buy)
function Disconnect(ply)
	saveStat(ply)
	SellAll(ply)
	if table.getn(player)<=0 then
		timer.Destroy("SaveStat")
	end
	Log(ply:Nick().." left the server.")
end
hook.Add( "PlayerDisconnected","playerdisconnected",Disconnect)
-- Player Spawn --
function GM:PlayerSpawn(ply)
    self.BaseClass:PlayerSpawn(ply)
    ply:SetGravity(0.75)
    ply:SetMaxHealth(100,true)
    ply:SetWalkSpeed(150)
	ply:SetRunSpeed(300)
	Loadout(ply)
end

-- Player Loadout --
 function Loadout(ply)
	ply:StripWeapons()
	-- Default SWEPS --
	ply:Give("weapon_physcannon")
	ply:Give("weapon_physgun")
	ply:Give("gmod_tool")
	for k,v in pairs(Jobs[ply:Team()][2]) do
		ply:Give(v)
	end
	if Jobs[ply:Team()][1]=="" then
		ply:SetModel("models/player/Group01/Male_0"..math.random(1,9)..".mdl")
	else
		ply:SetModel(tostring(Jobs[ply:Team()][1]))
	end
	return true
end
hook.Add("PlayerLoadout","Loadout",Loadout)

-- Jobs --
function SetJob(ply,command,args)
	if(tonumber(args[1])) then
		local teamno=tonumber(args[1])
		if ply:Team()==teamno then
			ply:ChatPrint("You are already a "..team.GetName(teamno))
			return
		end
		if(teamno==8||teamno==9||teamno==10) and ply:CanCP()!='true' then
			ply:ChatPrint("You are not able to become a "..team.GetName(teamno))
			return
		end
		if teamno==8||teamno==9 then
			tlim=math.floor((table.getn(player.GetAll())/4)+1)
		elseif teamno==10 then
			tlim=1
		else
			tlim=table.getn(player.GetAll())
		end
		if(team.NumPlayers(teamno)>=tlim) then
			ply:ChatPrint("Team limit reached.")
			return
		end
		ply:SetTeam(teamno)
		ply:ChatPrint("You have been made a "..team.GetName(teamno))
		local str=(ply:Nick().." has been made a "..team.GetName(teamno))
		Log(str)
		Loadout(ply)
	else
		if args[1]=="" then
			args[1]="."
		else
			args[1]=" "..args[1]
		end
		ply:ChatPrint("No such job"..args[1])
	end
end
concommand.Add("rp_job",SetJob)

-- F1 Menu --
function ShowHelp(ply)
	ply:ConCommand("rp_help")
	return false-- & ignore the default help panel
end
hook.Add("ShowHelp","Help",ShowHelp)
-- F2 Menu --
function ShowDoor(ply)
	ply:ConCommand("rp_doors")
end
hook.Add("ShowTeam","Doors",ShowDoor)
-- F3 Menu --
function ShowVoices(ply)
	ply:ConCommand("rp_voices")
end
hook.Add("ShowSpare1","Voices",ShowVoices)
-- F4 Menu --
function ShowMenu(ply)
	ply:ConCommand("rp_menu")
end
hook.Add("ShowSpare2","Menu",ShowMenu)


-- Log Function --
function Log(str)
	local Lfile="derp_logs/"..tostring(os.date("%d-%m-%y")..".txt")
	if not file.Exists(Lfile) then
		Msg("File "..Lfile.." does not exist. Creating...\n")
		file.Write(Lfile,tostring(os.date("%H:%M:%S")).." - "..str.."\n")
	else
		filex.Append(Lfile,tostring(os.date("%H:%M:%S")).." - "..str.."\n")
	end
	Msg(str.."\n")
end

-- Log Deaths --
function DeathLog(vic,wep,killer)
	if killer:IsPlayer() then
		killer=killer:Nick()
	else
		killer=killer:GetClass()
	end
	if vic:IsPlayer() then
		victim=vic:Nick()
	else
		victim=tostring(vic:GetClass())
	end
	local logstr=(victim.." was killed by "..tostring(killer))
	Log(logstr)
end
hook.Add("PlayerDeath","playerDeathLog",DeathLog)
hook.Add("OnNPCKilled","npcDeathLog",DeathLog)

function PlayerChat(ply,text,team,dead)
	if(string.sub(text,1,3)=="// ")then
		Log(ply:Nick().." [Global]: "..string.sub(text,3))
		return "[OOC]"..string.sub(text,3)
	else
		local ents=ents.FindInSphere(ply:EyePos(),250)
		local filter=RecipientFilter()
		filter:RemoveAllPlayers()
		for k,v in pairs(ents) do
			if v:IsPlayer() then
				filter:AddPlayer(v)
				Log(ply:Nick().." [Local]: "..text)
			end
		end
		if(ply:Team()>=8) then name="Unit "..ply:UniqueID() else name=ply:GetNWString("rpname") end
		SendUserMessage("ChatMsg",filter,text,name)
		return false
	end
end
hook.Add("PlayerSay","PlayerChat",PlayerChat)

function PropSpawn(ply,mdl)
	if table.HasValue(banned_props,mdl) then
		ply:ChatPrint("Sorry that prop is not available.")
		ply:EmitSound("buttons/button10.wav",1,100)
		return false
	else
		if ply:Team()<8 and ply:CheckFunds(10) then ply:TakeMoney(10) else return end
	end
end
hook.Add("PlayerSpawnProp","PropSpawn",PropSpawn)

function GM:PlayerSpawnSWEP(ply,class,swep)
	if !ply:IsAdmin() then
		return false
	end
end
function GM:PlayerGiveSWEP(ply,class,swep)
	if !ply:IsAdmin() then
		return false
	end
end
function GM:PlayerSpawnSENT(ply,class)
	if !ply:IsAdmin() then
		return false
	end
end

-- Doors --
doors={}
function SendDoorInfo()
	ply=player.GetAll()
	datastream.StreamToClients(ply,"GetDInfo",doors)
end
function DoorsSetUp()
	doors={}
	if(!sql.TableExists("doors"))then
		Msg("Doors table doesn't exist. Creating...")
		sql.Query("CREATE TABLE doors (ID varchar(255), Owner varchar(255))")
	end
	Dquery=sql.Query("SELECT * FROM doors")
	for k,v in pairs(Dquery) do
		RunString("doors["..v['ID'].."]=\"None\"")
	end
end
hook.Add("Initialize","SetUpDoors",DoorsSetUp)
function SetOwnable(ply,cmd,args)
	if not ply:IsAdmin() then
		ply:ChatPrint("You do not have the rights to do that.")
		return false
	end
	local tr=ply:GetEyeTraceNoCursor()
	if tr.Entity:GetClass()=="prop_door_rotating" then
		local ID=tr.Entity:EntIndex()
		local query=sql.Query("SELECT * from doors WHERE ID='"..ID.."'")
		if !query then
			RunString("doors["..ID.."]=\"None\"")
			ply:ChatPrint("Door set as ownable.")
		else
			sql.Query("DELETE FROM doors WHERE ID='"..ID.."'")
			table.remove(doors,ID)
			ply:ChatPrint("Door removed as ownable.")
		end
	else
		ply:ChatPrint(tostring(tr.Entity))
	end	
end
concommand.Add("rp_setownable",SetOwnable)
function ToggleDoor(ply,cmd,args)
	local tr=ply:GetEyeTraceNoCursor()
	if tr.Entity:GetClass()=="prop_door_rotating" then
		local ID=tr.Entity:EntIndex()
		local query=sql.Query("SELECT * FROM doors WHERE ID='"..ID.."'")
		if(!query) then ply:ChatPrint("That door is not ownable.") return end
		local owner=doors[ID]
		if(owner=="None")then
			ply:TakeMoney(20)
			ply:ChatPrint("You have bought this door for 20 credits.")
			RunString("doors["..ID.."]=\""..ply:UniqueID().."\"")
			SendDoorInfo()
		elseif owner==ply:UniqueID() then
			ply:AddMoney(15)
			ply:ChatPrint("You have sold this door for 15 credits.")
			RunString("doors["..ID.."]=\"None\"")
			SendDoorInfo()
		else
			ply:ChatPrint("That door is already owned by "..player.GetByUniqueID(owner):GetNWString("rpname")..".")
		end
	end
end
concommand.Add("rp_doortoggle",ToggleDoor)
function SellAll(ply,cmd,args)
	local query=sql.Query("SELECT * FROM doors WHERE Owner='"..tostring(ply:UniqueID()).."'")
	if query then
		tot=0
		for k,v in pairs(query) do
			sql.Query("UPDATE doors SET Owner='None' WHERE ID='"..v['ID'].."'")
			RunString("doors["..v['ID'].."]=\"None\"")
			ply:AddMoney(15)
			tot=tot+1
		end
		ply:ChatPrint("You have sold all your doors for "..(tot*15).." credits.")
	end
end
concommand.Add("rp_SellDoors",SellAll)

-- Voices --
function PlyVoice(ply,cmd,args)
	ply:EmitSound(args[2],100,100)
	ply:ConCommand("say "..args[1])
end
concommand.Add("rp_voice",PlyVoice)

-- Uber 1337 Windows Script --
function RespawnWindows(ent,inflictor,attacker,amount)
	for k,v in pairs(ents.FindByClass("func_breakable_surf")) do
		if v:Health()<=0 then
			local window=ents.GetByIndex(v:EntIndex())
			window:Spawn()
			window:SetSolid(SOLID_VPHYSICS)
			window:SetNotSolid(false)
		end
	end
end
timer.Create("WindowSpawn",30,0,RespawnWindows)

-- CP/Combines Nightvision --
function GM:PlayerSwitchFlashlight(ply)
	if(ply:Team()>=8) then
		ply:ConCommand("nightvision")
		return
	end
end